<template>
	<div class="system-menu-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="580px">
			<el-form ref="menuDialogFormRef" :model="state.ruleForm" size="default" label-width="80px">
				<el-row :gutter="35">

						<el-form-item label="上级菜单">
							<el-cascader
								:options="showMenuData"
								:props="{ checkStrictly: true, value: 'id', label: 'name' }"
								placeholder="请选择上级菜单"
								clearable
								class="w100"
								v-model="state.ruleForm.pid"
							>
								<template #default="{  data }">
									<span>{{ data.name }}</span>
								</template>
							</el-cascader>
						</el-form-item>

						<el-form-item label="菜单名称" prop="name">
							<el-input v-model="state.ruleForm.name" placeholder=""></el-input>
						</el-form-item>
                        <el-form-item label="权限代码" prop="code">
                            <el-input v-model="state.ruleForm.code" placeholder="格式：api/saas/index"></el-input>
                        </el-form-item>
                        <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                            <el-form-item label="排序" prop="code">
                                <el-input v-model="state.ruleForm.sort" placeholder=""></el-input>
                            </el-form-item>
                        </el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="systemMenuDialog">
import {defineAsyncComponent, reactive, onMounted, ref, defineProps, computed, nextTick} from 'vue';
import { storeToRefs } from 'pinia';
import { useRoutesList } from '/@/stores/routesList';
// import { setBackEndControlRefreshRoutes } from "/@/router/backEnd";

import { useMenuApi } from "/@/api/permission/menu";
import {deepClone} from "/@/utils/other";
const menuApi = useMenuApi();

const props = defineProps(['menuData']);
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 引入组件
const IconSelector = defineAsyncComponent(() => import('/@/components/iconSelector/index.vue'));

const showMenuData = computed(() => {
    const menuData = JSON.parse(JSON.stringify(props.menuData));
    menuData.unshift({ id: 0, name: '顶级菜单', children:[] });
    return menuData;
});

// 定义变量内容
const menuDialogFormRef = ref();
const stores = useRoutesList();
const { routesList } = storeToRefs(stores);
const state = reactive({
	// 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由菜单格式
	ruleForm: {
		name:"",
        code:"",
        pid: 0,
        sort: 100,
	},
	menuData: [], // 上级菜单数据
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

// 获取 pinia 中的路由
const getMenuData = (routes) => {
	const arr = [];
	routes.map((val) => {
		val['title'] = val.meta?.title;
		arr.push({ ...val });
		if (val.children) getMenuData(val.children);
	});
	return arr;
};
// 打开弹窗
const openDialog = (type, row) => {
	if (type === 'edit') {
		// 模拟数据，实际请走接口
		state.ruleForm.code = row.code;
        state.ruleForm.name = row.name;
        state.ruleForm.pid = row.pid;
        state.ruleForm.id = row.id;
        state.ruleForm.sort = row.sort;

		state.dialog.title = '修改菜单';
		state.dialog.submitTxt = '修 改';
	} else {
        state.ruleForm.code = 'lxs/saas/';
        state.ruleForm.name = '';
        delete state.ruleForm?.id;
        state.ruleForm.sort = 100;
		state.dialog.title = '新增菜单';
		state.dialog.submitTxt = '新 增';
        state.ruleForm.pid = row?.id || 0;
		// 清空表单，此项需加表单验证才能使用
		nextTick(() => {
			menuDialogFormRef.value.resetFields();
		});
	}
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
    const params = deepClone(state.ruleForm)
    if(typeof params.pid == 'object') {
        params.pid = params.pid[params.pid.length - 1];
    }
	if (state.dialog.type === 'add') {
        // 新增菜单
        menuApi.addMenu(params).then(() => {
            closeDialog(); // 关闭弹窗
            emit('refresh');
        });
    }else {
        // 修改菜单
        menuApi.editMenu(params).then(() => {
            closeDialog(); // 关闭弹窗
            emit('refresh');
        });
    }
};
// 页面加载时
onMounted(() => {
	state.menuData = getMenuData(routesList.value);
});

// 暴露变量
defineExpose({
	openDialog,
});
</script>
